package service

import (
	"gitee.com/kudingc/role_proxy/common"
	"gitee.com/kudingc/role_proxy/models"
	"gitee.com/kudingc/role_proxy/service/util"
	"github.com/gin-gonic/gin"
)

func Login(loginReq models.LoginReq) models.Res {
	var userRes models.LoginRes
	var state int
	var msg string

	//先检查验证码
	if common.CheckCaptcha && !util.CaptchaVerifyHandle(loginReq.CaptchaId, loginReq.CaptchaValue) {
		return models.Res{
			State: models.StateErr,
			Msg:   "captcha is invalid",
		}
	}
	loginReq.Passwd = util.GetMd5String([]byte(loginReq.Passwd))
	user, menuList, err := loginReq.CheckUser()
	if err != nil {
		state, msg = util.ErrHandle(err)
		return models.Res{
			State: state,
			Msg:   msg,
		}
	}
	tknStr := util.CreateJwtToken(util.Credentials{
		UserId:   user.Id,
		UserCode: user.UserCode,
		UserName: user.UserName,
	})
	if err = util.RedisSetStr(util.RedisTknKeyPrefix+user.UserCode+user.UserName, tknStr); err != nil {
		state, msg = util.ErrHandle(err)
		return models.Res{
			State: state,
			Msg:   msg,
		}
	}
	userRes.UserId = user.Id
	userRes.UserCode = user.UserCode
	userRes.UserName = user.UserName
	userRes.Authorization = tknStr
	userRes.MenuList = menuList

	return models.Res{
		State: models.StateOk,
		Msg:   "login success",
		Data:  userRes,
	}

}

func Logout(c *gin.Context) (res models.Res) {
	var jwt *util.Claims

	// 解析jwt
	if jwt, _ = util.CheckAuthorization(c); jwt == nil {
		res.State = models.StateErr
		res.Msg = "Token 验证失败"
		return
	}

	util.RedisDelKey(util.RedisTknKeyPrefix + jwt.Credentials.UserCode + jwt.Credentials.UserName)
	res.State = models.StateOk
	res.Msg = "logout success"
	return
}
